<?php
/**
 * @brief 定时任务
 */
class Crontab {
    public static function start() {
        $config = \Config::get('crontab', false);
        $confArray = $config ? $config->toArray() : [];

        if (isset($confArray['is_start']) && $confArray['is_start'] == true) {
            unset($confArray['is_start']);

            //定期清理碎片内存
            \Swoole\Timer::tick(3600000, function () {
                $memory = memory_get_usage();
                gc_mem_caches();
            });

            $data = array_group($confArray ?? [], 'time');
            self::startTimer($data);
        }
    }

    private static function startTimer($data) {
        $parser = new \Crontab\Parser();
        $timerTimes = [];
        $timerTimeTasks = [];
        foreach ($data as $cronTime => $val) {
            if ($res = $parser->parse($cronTime)) {
                $timerTimes[$cronTime] = $res;
                $timerTimeTasks[$cronTime] = $val;
            }
        }

        if ($timerTimes && $timerTimeTasks) {
            \Swoole\Timer::tick(1000, function () use ($timerTimes, $timerTimeTasks, $parser) {
                $thisTime = time();
                foreach ($timerTimes as $cronTime => $timerTime) {
                    if (isset($timerTimeTasks[$cronTime]) && $parser->check($thisTime, $timerTime)) {
                        foreach ($timerTimeTasks[$cronTime] as $timerTimeTask) {
                            Yaf_Loader::import(APP_PATH . '/application/crontabs/' . $timerTimeTask['class'] . '.php');
                            \Swoole\Timer::after(1, function () use ($timerTimeTask, $thisTime) {
                                $className = 'App\Crontab\\' . $timerTimeTask['class'];
                                $class = new $className();
                                $func = $timerTimeTask['func'];
                                $class->$func();
                            });
                        }
                    }
                }
            });
        }
    }
}
